package org.okami.shop.apigateway.orders.pc;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;

/**
 * @author: TanJingyu
 * @create: 2020-12-29 10:54
 **/
@Configuration
public class OrderPcConfiguration {

    @Bean
    public OrderHandler orderHandler(WebClient webClient) {
        return new OrderHandler(webClient);
    }

    @Bean
    public RouteLocator orderProxyRouting(RouteLocatorBuilder builder) {
        String url = "http://localhost:8080";
        return builder.routes()
                .route(r -> r.path("/orders").and().method("POST").uri(url))
                .route(r -> r.path("/orders").and().method("PUT").uri(url))
                .route(r -> r.path("/orders/**").and().method("POST").uri(url))
                .route(r -> r.path("/orders/**").and().method("PUT").uri(url))
                .route(r -> r.path("/orders").and().method("GET").uri(url))
                .build();
    }

    @Bean
    public RouterFunction<ServerResponse> orderHandlerRouting(OrderHandler orderHandler) {
        return RouterFunctions.route(GET("/orders/{orderId}"), orderHandler::getOrderDetails);
    }

    @Bean
    public WebClient webClient() {
        return WebClient.create();
    }
}
